package cn.innosmart.aq.camera;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.tutk.IOTC.AVIOCTRLDEFs;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import cn.innosmart.aq.R;

/**
 * 设置局域网wifi的列表适配器
 * Created by David on 2015/12/29.
 */
public class MyCameraWifiListAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Context context;
    private ArrayList<AVIOCTRLDEFs.SWifiAp> wifis;

    /**
     * 构造函数
     *
     * @param context
     * @param wifis   摄像头搜索到的wifi列表
     */
    public MyCameraWifiListAdapter(Context context, ArrayList<AVIOCTRLDEFs.SWifiAp> wifis) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
        this.wifis = wifis;
    }

    @Override
    public int getCount() {
        return wifis.size();
    }

    @Override
    public Object getItem(int position) {
        return wifis.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.listview_wifi_list, null);
            holder.tvWifi = (TextView) convertView.findViewById(R.id.tv_ssid);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AVIOCTRLDEFs.SWifiAp wifiAp = wifis.get(position);

//        System.out.println("wifi ap name: " + wifiAp.name + "," + wifiAp.name.getBytes());
//
//        for (int j=0; j<wifiAp.name.getBytes().length; j++) {
//            System.out.format("%02X ", wifiAp.name.getBytes()[j]);
//        }
//        System.out.println();

        byte[] nameBytes = wifiAp.name.getBytes();
        int pos = 0;
        for(int i = 0; i<nameBytes.length; i++) {
            if(nameBytes[i] == 0) {
                pos = i;
            }
        }

        if(pos == 0) {
            pos = nameBytes.length - 1;
        }

        byte[] nameBytesFixed = new byte[pos+1];
        System.arraycopy(nameBytes, 0, nameBytesFixed, 0, pos);
        String wifiAPName = null;
        try {
            wifiAPName = new String(nameBytesFixed, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        holder.tvWifi.setText(wifiAPName);
        return convertView;
    }

    static class ViewHolder {
        TextView tvWifi;
    }
}
